package com.woniuxy.portal.service.impl;

import com.woniuxy.common.RedisConst;
import com.woniuxy.portal.model.entity.Book;
import com.woniuxy.portal.model.vo.CartItemVo;
import com.woniuxy.portal.model.vo.CartVo;
import com.woniuxy.portal.service.BookService;
import com.woniuxy.portal.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * @author yellow Docter
 * @date 2024-10-25
 * @desc 蜗牛创想：www.woniuxy.com
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate<String,CartVo> redisTemplate;

    @Autowired
    private BookService bookService;

    @Override
    public CartVo getCart(Long userId) {

        //从redis 获取数据
        String key = RedisConst.USER_CART_PREFIX + ":" + userId;
        CartVo cartVo = redisTemplate.opsForValue().get(key);

        if (cartVo == null){
            cartVo = new CartVo();
            cartVo.setUserId(userId);
            redisTemplate.opsForValue()
                    .set(key,cartVo);
        }
        return cartVo;
    }

    @Override
    public CartVo addCartItem(Long userId, Long bookId) {

        //1、从redis 拿到购物车
        CartVo cartVo = getCart(userId);
        //2、从数据库拿到book
        Book book = bookService.getById(bookId);
        //3、把book 转成 CartItemVo

        CartItemVo cartItemVo = new CartItemVo(
                userId,   //用户id
                bookId,
                book.getName(),
                book.getImgSrc(), //图片
                book.getPrice(),
                1);   //数量

        cartVo.add(cartItemVo);
        //4、存储到redis中
        redisTemplate.opsForValue().set(
                RedisConst.USER_CART_PREFIX + ":" + userId,
                cartVo,
                Duration.ofDays(7)
        );

        return cartVo;
    }

    @Override
    public CartVo removeCartItem(Long userId, Long bookId) {
        return null;
    }

    @Override
    public void clearCart(Long userId) {
        String key = RedisConst.USER_CART_PREFIX + ":" + userId;
        redisTemplate.opsForValue().getOperations().delete(key);
        log.info("清除购物车");
    }
}
